<template>
	<div class="container">
	  <div class="comment" v-for="item in comments" :key="item.id">
		<div class="info">
		  <img class="avatar" :src="item.fromAvatar" width="36" height="36"/>
		  <div class="right">
			<div class="name">{{ item.fromName }}</div>
			<div class="date">{{ item.date }}</div>
		  </div>
		</div>
		<div class="content">{{ item.content }}</div>
		<div class="control">
			<span class="like" :class="{ active: item.isLike }" @click="likeClick(item)">
				<i class="iconfont icon-like"></i>
				<el-icon><Promotion /></el-icon>
				<span class="like-num">{{ item.likeNum > 0 ? item.likeNum + '人赞' : '赞' }}</span>
			</span>
			<span class="comment-reply" @click="showCommentInput(item)">
				<i class="iconfont icon-comment"></i>
				<el-icon><Comment /></el-icon>
				<span>回复</span>
			</span>
			<span v-if="userInfo.userRole.includes('ROLE_ADMIN')" class="comment-delete" @click="deleteComment(item, 0)">
				<i class="iconfont icon-delete"></i>
				<el-icon><DeleteFilled /></el-icon>
				<span>删除</span>
			</span>
			</div>
		<div class="reply">
		  <div class="item" v-for="reply in item.reply" :key="reply.id">
			<div class="reply-content">
			  <span class="from-name">{{ reply.fromName }}</span><span>: </span>
			  <span class="to-name">@{{ reply.toName }}</span>
			  <span>{{ reply.content }}</span>
			</div>
			<div class="reply-bottom">
			  <span>{{ reply.date }}</span>
			  <span class="reply-text" @click="showCommentInput(item, reply)">
				<i class="iconfont icon-comment"></i>
				<el-icon><Comment /></el-icon>
				<span>回复</span>
			  </span>
			  <span v-if="userInfo.userRole.includes('ROLE_ADMIN')" class="delete-reply" @click="deleteComment(reply, 1)">
				<i class="iconfont icon-delete"></i>
				<el-icon><DeleteFilled /></el-icon>
				<span>删除</span>
			</span>
			</div>
		  </div>
		  <div class="write-reply" v-if="Array.isArray(item.reply) && item.reply.length > 0" @click="showCommentInput(item)">
			<i class="el-icon-edit"></i>
			<span class="add-comment">添加新评论</span>
		  </div>
		  <transition name="fade">
			<div class="input-wrapper" v-if="showItemId === item.id">
			  <el-input class="gray-bg-input"
						v-model="inputComment"
						type="textarea"
						:rows="3"
						autofocus
						placeholder="写下你的评论">
			  </el-input>
			  <div class="btn-control">
				<span class="cancel" @click="cancel">取消</span>
				<el-button class="btn" type="success" round @click="commitComment(item)">确定</el-button>
			  </div>
			</div>
		  </transition>
		</div>
	  </div>
  
	  <!-- Element UI 分页器 -->
	  <div class="pagination-wrapper">
		<!-- 页码选择器 -->
		<el-pagination
		  :total="totalComments"
		  :page-size="pageSize"
		  :current-page="currentPage"
		  @current-change="handlePageChange"
		  @size-change="handlePageSizeChange" 
		  layout="total, sizes, prev, pager, next, jumper"
		  :page-sizes="[5, 7, 10]"
		  class="pagination">
		</el-pagination>
	  </div>
	</div>
  </template>
  
  <script>
  import { getComments ,likeComments, addReply, deleteComments} from "@/api/comment/index.js"; // 导入
  export default {
	props: {
    // 接收父组件传来的当前登录用户的信息
    userInfo: {
      type: Object,
      required: true
    },
    isAll: {
      type: Number, // 指定为Number类型，以确保传递的是整数或浮点数
      required: true
    },
    type: {
      type: Number, // 指定为Number类型，以确保传递的是整数或浮点数
      required: true
    }
  },
	data() {
	  return {
		inputComment: '',
		showItemId: '',
		comments: [], // 评论数据
		totalComments: 0, // 评论总数
		currentPage: 1, // 当前页
		pageSize: 2, // 默认每页显示5个评论
	  };
	},
	methods: {
	  /**
	   * 点赞
	   */
	   async likeClick(item) {
			try {
				// 发送请求到后端，更新点赞状态
				const response = await likeComments(item.id);
				if (!response.code) {
				// 根据后端返回的 count 更新点赞数
				item.likeNum = response.data;
				if(response.count == 1){
				// 成功提示（可选）
				this.$message.success("点赞成功");
				}else{
					this.$message.success("取消点赞成功");
				}
				} else {
				// 处理错误情况
				this.$message.error("操作失败");
				}
			} catch (error) {
				console.error('点赞/取消点赞失败:', error);
				this.$message.error('网络错误，请稍后再试');
			}
},
  
	  /**
	   * 点击取消按钮
	   */
	  cancel() {
		this.showItemId = '';
	  },
  
	  /**
	   * 提交评论
	   */
	  async commitComment(item) {
		console.log(this.inputComment);
		console.log(item)
		console.log(this.userInfo)
    const replyDTO = {
		commentId: item.id,
        fromId: this.userInfo.uid, // 需要替换为实际的用户学号
        content: this.inputComment,
        fromName: this.userInfo.username, // 可能需要根据实际情况调整
		toId: item.fromId,
		toName: item.fromName,
    };
    console.log(replyDTO)
    try {
        let data = await addReply(replyDTO);
        if (!data.code) {
          // 调用子组件的方法来刷新评论列表
          this.fetchComments();
          this.$message.success('评论成功');
		  this.inputComment= ""
        } else {
          this.$message.error('评论失败，请重试');
        }
    } catch (error) {
        console.error('添加评论失败:', error);
        // 错误处理
    }
},
		//管理员删除留言
		async deleteComment(item, type){
			console.log(item)
			console.log(type)
			try{
				let data = await deleteComments(type, item.id);
				if(!data.code){
				// 调用子组件的方法来刷新评论列表
				this.fetchComments();
				this.$message.success('删除成功');					
				}
			}catch(error){
				console.error('添加评论失败:', error);
			}
		},

	  /**
	   * 点击评论按钮显示输入框
	   * item: 当前大评论
	   * reply: 当前回复的评论
	   */
	  showCommentInput(item, reply) {
		if (reply) {
		  this.inputComment = "@" + reply.fromName + " ";
		} else {
		  this.inputComment = '';
		}
		this.showItemId = item.id;
	  },
  
	  /**
	   * 获取评论数据
	   */
	  async fetchComments() {
		try {
				const response = await getComments(this.isAll, this.type, this.currentPage, this.pageSize);
				this.comments = response.data;
				this.totalComments = response.count; // 设置总评论数
			} catch (error) {
				console.error('获取留言数据成功:', error);
			}
	  },
  
	  /**
	   * 处理页码变化
	   */
	  handlePageChange(page) {
		this.currentPage = page;
		this.fetchComments(); // 当页码变化时重新加载评论数据
	  },
  
	  /**
	   * 处理每页显示条数变化
	   */
	  handlePageSizeChange(size) {
		this.pageSize = size;
		this.fetchComments(); // 更新每页条数后重新加载数据
	  }
	},
	created() {
	  this.fetchComments(); // 组件创建时获取评论数据
	}
  };
  </script>
  
  <style scoped lang="scss">
  
	@import "@/styles/comment.scss";
  
	.container {
		display: flex;
		flex-direction: column;
		gap: 10px;
		height: 80vh; /* 设置容器的高度为视口的80%，你可以根据需要调整 */
		overflow-y: auto; /* 启用容器的垂直滚动条 */
	  .comment {
		max-height: 100%; /* 确保每条评论区域可以在容器内完整显示 */
    	align-items: flex-start; /* 水平对齐顶部 */
    	padding: 10px;
    	border-bottom: 1px solid #e0e0e0;
    	box-sizing: border-box;
		.info {
		  display: flex;
		  align-items: center;
		  .avatar {
			border-radius: 50%;
		  }
		  .right {
			
			display: flex;
			flex-direction: column;
			margin-left: 10px;
			.name {
			  font-size: 16px;
			  color: $text-main;
			  margin-bottom: 5px;
			  font-weight: 500;
			}
			.date {
			  font-size: 12px;
			  color: $text-minor;
			}
		  }
		}
		.content {
		  font-size: 16px;
		  width: 100%;
		  color: $text-main;
		  line-height: 20px;
		  padding: 10px 0;
		}
		.control {
		  width: 100%;
		  display: flex;
		  align-items: center;
		  font-size: 14px;
		  color: $text-minor;
		  .like {
			display: flex;
			align-items: center;
			margin-right: 20px;
			cursor: pointer;
			&.active, &:hover {
			  color: $color-main;
			}
			.iconfont {
			  font-size: 14px;
			  margin-right: 5px;
			}
		  }
		  .comment-reply {
			display: flex;
			align-items: center;
			cursor: pointer;
			&:hover {
			  color: $text-333;
			}
			.iconfont {
			  font-size: 16px;
			  margin-right: 5px;
			}
		  }
		  .comment-delete{
			display: flex;
			align-items: center;
			cursor: pointer;
			&:hover {
			  color: $color-danger;
			}
			.iconfont {
			  font-size: 16px;
			  margin-right: 20px;
			}			
		  }
  
		}
		.reply {
		  margin: 10px 0;
		  border-left: 2px solid $border-first;
		  .item {
			margin: 0 10px;
			padding: 10px 0;
			border-bottom: 1px dashed $border-third;
			.reply-content {
			  display: flex;
			  align-items: center;
			  font-size: 14px;
			  color: $text-main;
			  .from-name {
				color: $color-main;
			  }
			  .to-name {
				color: $color-main;
				margin-left: 5px;
				margin-right: 5px;
			  }
			}
			.reply-bottom {
			  display: flex;
			  align-items: center;
			  margin-top: 6px;
			  font-size: 12px;
			  color: $text-minor;
			  .reply-text {
				display: flex;
				align-items: center;
				margin-left: 10px;
				cursor: pointer;
				&:hover {
				  color: $text-333;
				}
				.icon-comment {
				  margin-right: 5px;
				}
				.icon-delete{
					margin-right: 5px;
				}
			  }
			  .delete-reply{
				display: flex;
				align-items: center;
				margin-left: 10px;
				cursor: pointer;
				&:hover {
				  color: $text-333;
				}
				.icon-comment {
				  margin-right: 5px;
				}
				.icon-delete{
					margin-right: 5px;
				}				
			  }
			}
		  }
		  .write-reply {
			display: flex;
			align-items: center;
			font-size: 14px;
			color: $text-minor;
			padding: 10px;
			cursor: pointer;
			&:hover {
			  color: $text-main;
			}
			.el-icon-edit {
			  margin-right: 5px;
			}
		  }
		  .fade-enter-active, fade-leave-active {
			transition: opacity 0.5s;
		  }
		  .fade-enter, .fade-leave-to {
			opacity: 0;
		  }
		  .input-wrapper {
			padding: 10px;
			.gray-bg-input, .el-input__inner {
			  /*background-color: #67C23A;*/
			}
			.btn-control {
			  display: flex;
			  justify-content: flex-end;
			  align-items: center;
			  padding-top: 10px;
			  .cancel {
				font-size: 16px;
				color: $text-normal;
				margin-right: 20px;
				cursor: pointer;
				&:hover {
				  color: $text-333;
				}
			  }
			  .confirm {
				font-size: 16px;
			  }
			}
		  }
		}
	  }
	}
</style>